import cquery from '@dfeidao/atom-nodejs/db/complex-query';
import format from '@dfeidao/atom-nodejs/dt/format';
import { IncomingHttpHeaders } from 'http';
import { systemid } from '../atom/config';

interface Message {
	filter: {
		teacher_no: string;
		auditor_status: string[];
	};
}

interface IWebResult {
	data: unknown;
	cookie?: {
		[name: string]: string;
	} | null;
	content_type?: string;
	headers?: {
		[key: string]: string[];
	};
	attachment?: string;
	redirect?: string;
	status_code?: number;
}

interface I {
	class_id: string;
	student_no: string;
	start_time: number;
	start_times: string;
	finish_time: number;
	finish_times: string;
	student_name: string;
	submission_time: number;
	submission_times: string;
}

export default async function atom(message: Message, action_id: string, session_id: string, headers: IncomingHttpHeaders): Promise<IWebResult> {

	const cq = cquery(action_id, session_id, systemid);
	const d = await cq
		.add_field('student_leave', 'student_no', 'student_no')
		.add_field('student_leave', 'student_name', 'student_name')
		.add_field('student_leave', 'start_time', 'start_time')
		.add_field('student_leave', 'finish_time', 'finish_time')
		.add_field('student_leave', 'submission_time', 'submission_time')
		.add_field('student_leave', 'auditor_status', 'auditor_status')
		// .add_field('student_leave', 'productid', 'productid')
		.outer_left_join('student_leave', 'class_student', ['student_no', 'student_no'])
		.outer_left_join('class_student', 'class_teacher', ['class_id', 'class_id'])
		.where_eq('class_teacher', 'teacher_no', message.filter.teacher_no)
		.where_in('student_leave', 'auditor_status', message.filter.auditor_status)
		.orderby_desc('submission_time')
		.exec();

	d.forEach((i: I) => {
		i.start_times = format(i.start_time, 'YYYY-MM-DD aa');
		i.finish_times = format(i.finish_time, 'YYYY-MM-DD aa');
		i.submission_times = i.submission_time ? format(i.submission_time, 'YYYY-MM-DD') : '';
		i.student_name = (i.student_name || '') + '提交的请假';
	});
	return { data: d } as IWebResult;
}
